<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Comment extends CI_Controller {
    function __controller() {
        parent::Controller();
    }

    public function add($id = 0) {
 

        $text = strip_tags($this -> input -> post('text'), '');
        $email = $this -> input -> post('email');
        $name = strip_tags($this -> input -> post('name'), '');

       $ch =  $this -> valid($email, $name, $text);
       
       if($ch == true){
        $this -> load -> model('Comment_modul', 'comment');
        $id =   $this -> comment->save($id,$text,$email,$name);
        
        
        
        $json["who"] = 'comment';
 
        $json["id"] = $data['comments_date']['0']['id']=$id;
        $data['comments_date']['0']['time']= date("d.m.Y",time());
        $data['comments_date']['0']['name']= $name;
        $data['comments_date']['0']['text']= $text;
        
        
        $json["html"] =  $this -> load -> view('comments/listcom',$data,true); 
        
         
        echo json_encode($json);
           
       }
        
        
        return;
    }

    public function valid($email, $name, $text) {

        // check email
        if (!empty($email)) {
            if (preg_match("|^[-0-9a-z_\.]+@[-0-9a-z_^\.]+\.[a-z]{2,6}$|i", $email)) {

                if (strlen($name) > 3) {

                    if (strlen($text) > 20) {


                                  $robot = '/www.|www|http|порно|sex|anal|free/';
                        if (preg_match($robot, $text)) {
                            $json["text"] = "Робот не пропускает Ваш текст";

                        } else {
                          return true;
                        }

                    } else {
                        $json["text"] = "Текст комментария слишком короткий";

                    }

                } else {
                    $json["text"] = "Имя короткое";

                }

            } else {
                $json["text"] = "E-mail не корректен";
            }
        } else {
            $json["text"] = "Введите Ваш E-mail";
        }
        $json["who"] = 'mes';
        echo json_encode($json);
        #      echo     json_decode($json);

        return;
    }

    public function jsOnResponse($obj) {
        echo "<script type='text/javascript'>
         window.parent.onResponse('" . $obj . "'); 
         </script>";
        return;
    }

}
